// utils/router-guard.js
import TabBarManager from './tabbar-manager'
import { logintoken } from '../stores/loginToken/loginToken'

class RouterGuard {
  publicPages = ['/pages/login/login']

  async beforeEach(to, from, next) {
    console.log(`🛣️ 路由跳转: ${from?.path || 'null'} -> ${to.path}`)

    // 1. 是否是公共页面
    if (this.isPublicPage(to.path)) {
      next()
      return
    }

    // 2. 检查登录状态
    const loginToken = logintoken()
    const token = loginToken.token
    if (!token) {
      console.log('❌ 未登录，跳转到登录页')
      this.redirectToLogin()
      return
    }

    // 3. 检查权限
    if (!TabBarManager.hasPagePermission(to.path)) {
      console.log('❌ 无页面访问权限')
      this.showNoPermission()
      return
    }

    next()
  }

  isPublicPage(path) {
    return this.publicPages.some(p => path === p || path.startsWith(p + '?'))
  }

  redirectToLogin() {
    wx.redirectTo({
      url: '/pages/login/login'
    })
  }

  showNoPermission() {
    wx.showModal({
      title: '无权限访问',
      content: '您没有权限访问该页面，请联系管理员',
      showCancel: false,
      success: () => {
        const hasIndex = TabBarManager.hasPagePermission('/pages/index/index')
        if (hasIndex) {
          wx.switchTab({ url: '/pages/index/index' })
        } else {
          wx.navigateBack()
        }
      }
    })
  }

  // 主动触发守卫检查
  async checkRoute(toPath) {
    const fromPath = this.getCurrentPagePath()
    await this.beforeEach(
      { path: toPath },
      { path: fromPath },
      () => {} // next 不需要真正跳转，因为我们只是检查
    )
  }

  getCurrentPagePath() {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    if (!currentPage) return ''
    return '/' + currentPage.route // 注意加 '/'
  }
}

export default new RouterGuard()